package top.xxyu;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileHelper {

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	/**
	 * 删除根目录中的所有文件和子目录，保留根目录
	 *
	 * @param dir
	 */
	public static void deleteSubDir(File dir) {
		File[] destList = dir.listFiles();
		for (File f : destList) {
			deleteDir(f);
		}
	}

	/**
	 * 复制单个文件
	 *
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf.txt
	 * @return boolean
	 */
	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.isDirectory()) {
				return;
			}
			createFile(newPath);

			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[51200];
				int length;
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			} else {
				throw new RuntimeException("文件["+oldPath+"]不存在！");
			}
		} catch (Exception e) {
			System.out.println("复制文件操作出错:"+oldPath);
			e.printStackTrace();
		}

	}

	public static void createFile(String newPath) throws IOException{
		File newFile = new File (newPath);
		if(!newFile.exists()){
			File parent= newFile.getParentFile();
			if(!parent.exists()){
				parent.mkdirs();
			}
			newFile.createNewFile();
		}
	}

}
